package net.wlm.jtp.dwd.log.job;
import com.alibaba.fastjson.JSON;
import net.wlm.jtp.dwd.log.function.AdjustIsNewProcessFunction;
import net.wlm.jtp.dwd.log.function.LogSplitProcessFunction;
import net.wlm.jtp.dwd.log.util.KafkaUtil;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;
/**
 * DWD层数据应用开发：将ODS层采集原始日志数据，进行分类处理，存储Kafka队列，作为DWD层日志数据进一步分析。
 *      数据流向：kafka -> flink datastream -> kafka
 *      kafka-console-consumer.sh --bootstrap-server node101:9092 --topic topic-log
 *      kafka-console-producer.sh --bootstrap-server node101:9092 --topic topic-log
 *      kafka-topics.sh --bootstrap-server  node101:9092 --list
 */
public class JtpLogEtlJob {
    public static void main(String[] args) throws Exception {
        // 1.执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        // 2.数据源-source
        DataStream<String> kafkaDataStream = KafkaUtil.consumerKafka(env, "topic-log");
        //kafkaDataStream.print("kafka");
        // 3.数据转换-transformation
        // 4.数据输出-sink
        processLog(kafkaDataStream);
        // 5.触发执行-execute
        env.execute("JtpLogEtlJob");
    }
    private static void processLog(DataStream<String> logStream) {
        // 1-数据清洗
        DataStream<String> jsonStream = LogCleaned(logStream);
        // 2-新老访客状态标记修复
        DataStream<String> etlStream = processIsNew(jsonStream);
        // 3-数据分流
        DataStream<String> pageStream = splitStream(etlStream);
        // 4-存储数据
        KafkaUtil.producerKafka(pageStream, "dwd-traffic-page-log");
    }
    private static DataStream<String> processIsNew(DataStream<String> jsonStream) {
        // a-按照设备ID分组
        KeyedStream<String, String> midStream = jsonStream.keyBy(new KeySelector<String, String>() {
            @Override
            public String getKey(String value) throws Exception {
                return JSON.parseObject(value).getJSONObject("common").getString("mid");
            }
        });
        // b-状态编程，对is_new检验
        SingleOutputStreamOperator<String> isNewStream = midStream.process(new AdjustIsNewProcessFunction());
        // d-返回数据流
        return isNewStream;
    }
    private static DataStream<String> splitStream(DataStream<String> etlStream) {
        // a-侧输出流标记
        OutputTag<String> errorTag = new OutputTag<String>("error-log"){};
        OutputTag<String> startTag = new OutputTag<String>("start-log"){};
        OutputTag<String> displayTag = new OutputTag<String>("display-log"){};
        OutputTag<String> actionTag = new OutputTag<String>("action-log"){};
        // b-日志分流处理
        SingleOutputStreamOperator<String> pageStream =
                etlStream.process(new LogSplitProcessFunction(errorTag, startTag, displayTag, actionTag));
        // c-侧流输出
        DataStream<String> errorStream = pageStream.getSideOutput(errorTag);
        KafkaUtil.producerKafka(errorStream, "dwd-traffic-error-log");
        DataStream<String> startStream = pageStream.getSideOutput(startTag);
        KafkaUtil.producerKafka(startStream, "dwd-traffic-start-log");
        DataStream<String> displayStream = pageStream.getSideOutput(displayTag);
        KafkaUtil.producerKafka(displayStream, "dwd-traffic-display-log");
        DataStream<String> actionStream = pageStream.getSideOutput(actionTag);
        KafkaUtil.producerKafka(actionStream, "dwd-traffic-action-log");
        // e-主流输出
        return pageStream;
    }
    private static DataStream<String> LogCleaned(DataStream<String> logStream) {
        // a-脏数据侧边流输出时标记
        OutputTag<String> dirtyTag = new OutputTag<String>("dirty-log"){};
        SingleOutputStreamOperator<String> cleanedStream = logStream.process(new ProcessFunction<String, String>() {
            @Override
            public void processElement(String s, Context ctx, Collector<String> out) throws Exception {
                try {
                    // a.解析json数据
                    JSON.parseObject(s);
                    // b.没有异常，解析正确，正常输出
                    out.collect(s);

                } catch (Exception e) {
                    ctx.output(dirtyTag, s);
                }
            }
        });
        // c-侧边流输出
        DataStream<String> dirtyStream = cleanedStream.getSideOutput(dirtyTag);
        KafkaUtil.producerKafka(dirtyStream, "dwd-traffic-dirty-log");
        // d-返回正常数据流
        return cleanedStream;
    }
}